In this advance CSS tutorial, we will be going to learn the CSS object-fit property. We will also learn how to use this property to resize an image and video to fit in its parent container.
CSS object-fit Property
The
object-fit
property can be used on the
<img>
and
<video>
elements so they could fit in the parent element container. This property can either maintain the height-width ratio or stretch and shrink the element to fit it in the container. For instance, if an image is of 500X300 pixels and the container width and height ratio is 200X400, we can use the image height and width properties to set the image height and width according to the container area. But this could lead to image distortion. What if we only want to display that portion of the image that fits in the container box and cut off the rest of the sides. For that, we can use the
object-fit:cover
along with the width and height property. This will preserve the original image pixels.
Example
<!DOCTYPE html>
<html>
<head>
<style>
img {
width: 200px;
height: 200px;
object-fit: cover;
}
</style>
</head>
<body>
<img src="img.png" alt="image" >
</body>
</html>
CSS object-fit Property values
The
object-fit
property can accept one of these values.
Values | Description |
fill
|
It is the default value of
object-fit
property. The image or video element will cover the full size of the container box by shrinking or stretching the pixels.
|
contain
|
The element content is scaled, and it maintains the aspect ratio of the default element content. |
cover
|
It fit the container's element and maintains the actual aspect ratio of the element by cutting the unnecessary sides. |
none
|
It does not resize the replaced content. |
scale-down
|
The element content is sized between none and contain. |
Example
<!DOCTYPE html>
<html>
<head>
<style>
#fill {
width: 300px;
height: 300px;
object-fit: fill;
}
#contain {
width: 300px;
height: 300px;
object-fit: contain;
}
#cover {
width: 300px;
height: 300px;
object-fit: cover;
}
#scale-down {
width: 300px;
height: 300px;
object-fit: scale-down;
}
#none {
width: 300px;
height: 300px;
object-fit: none;
}
</style>
</head>
<body>
<h2>object-fit: fill </h2>
<img id="fill" src="a.jpg">
<h2>object-fit: contain</h2>
<img id="contain" src="a.jpg">
<h2>object-fit: cover</h2>
<img id="cover" src="a.jpg" >
<h2>object-fit: scale-down</h2>
<img id="scale-down" src="a.jpg" >
<h2>object-fit: none</h2>
<img id="none" src="a.jpg">
</body>
</html>
Summary
- The object-fit property defines how an image and video should be resized to fit in a container.
- To fit an image in a container, we could either shrink and stretch the image or cut the sides.
- By shrinking and stretching, the image quality decrease, and the aspect ratio distorts.
- But by cutting the image sides or presenting the default image keeps the image aspect ratio maintain.